﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Classified.Data.Repositories;
using Classified.Domain.Entities;
using Classified.Service;
using MvcPaging;

namespace Classified.Web.Areas.Admin.Controllers
{

    public class ClassifiedController : Controller
    {
        private readonly IClassifiedAdCategoryRepository _classifiedAdCategoryRepository;
        private readonly IClassifiedRepository _classifiedRepository;
        private readonly ISecurityService _securityService;
        private readonly IClassifiedPictureRepositories _classifiedPictureRepositories;
        private readonly ILocationRepository _locationRepository;
        private readonly ICategoryAttributeRepository _categoryAttributeRepository;
        private readonly IAttributeValueRepository _attributeValueRepository;
        private ICountryRepository _countryRepository { get; set; }
        private ICurrencyRepository _currencyRepository;
        private readonly IClasifiedAttributeRepository _clasifiedAttributeRepository;
        private readonly string domainName = ConfigurationManager.AppSettings["domainName"];



        public ClassifiedController(ISecurityService securityService,
            IClassifiedAdCategoryRepository classifiedAdCategoryRepository,
            IClassifiedRepository classifiedRepository,
            IClassifiedPictureRepositories classifiedPictureRepositories,
            ILocationRepository locationRepository,
            ICategoryAttributeRepository categoryAttributeRepository,
            IAttributeValueRepository attributeValueRepository,
            IClasifiedAttributeRepository clasifiedAttributeRepository,
            ICountryRepository countryRepository,
            ICurrencyRepository currencyRepository
            )
        {

            _securityService = securityService;
            _classifiedAdCategoryRepository = classifiedAdCategoryRepository;
            _classifiedRepository = classifiedRepository;
            _classifiedPictureRepositories = classifiedPictureRepositories;
            _locationRepository = locationRepository;
            _categoryAttributeRepository = categoryAttributeRepository;
            _attributeValueRepository = attributeValueRepository;
            _clasifiedAttributeRepository = clasifiedAttributeRepository;
            _countryRepository = countryRepository;
            _currencyRepository = currencyRepository;


        }

        //
        // GET: /Admin/Classified/



        public ActionResult Index()
        {
            return RedirectToAction("List");
        }
        public ActionResult List(int? page)
        {

            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var data = _classifiedRepository.GetAll().OrderByDescending(i => i.Id).ToPagedList(currentPageIndex, 10);
            return View(data);
        }
        [HttpPost]
        public ActionResult GetCategoryParent()
        {
            var category = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == 0).ToList();
            var guid = Guid.NewGuid();
            var data = category.Select(i => new ClassifiedCategory
                    {
                        Name = i.Name,
                        Id = i.Id,

                    });
            return Json(new { categoryparent = data, Guid = guid }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Create()
        {
            ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.DisplayOrder), "Id", "Name");
            ViewBag.UserId = new SelectList(_securityService.GetUsers().Where(x => x.IsActive), "Id", "UserName");

            var data = new ClassifiedAd();
            data.CreatedOnUtc = DateTime.UtcNow;
            data.UpdatedOnUtc = DateTime.UtcNow;
            data.SubmitDate = DateTime.UtcNow;
            return View(data);


        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ClassifiedAd model, List<int> CategoryParent, List<int> locationParent, List<int> AttributName, FormCollection formCollection)
        {


            var attributes = new List<ClassifiedCategoryAttribute>();

            foreach (var i in CategoryParent)
            {

                var data1 = _categoryAttributeRepository.GetMany(
                    x => x.CategoryId == i || x.CategoryId == i).ToList();
                attributes = attributes.Union(data1).ToList();
            }

            var locationId = 0;
            var categoryId = Convert.ToInt32(CategoryParent.LastOrDefault(x => x != 0));
            if (locationParent != null)
            {
                locationId = Convert.ToInt32(locationParent.LastOrDefault(x => x != 0));
            }

            if (categoryId != 0 && locationId != 0)
            {

                if (ModelState.IsValid)
                {
                    model.SubmitDate = DateTime.UtcNow;
                    model.CreatedOnUtc = DateTime.UtcNow;
                    model.UpdatedOnUtc = DateTime.UtcNow;
                    model.CategoryId = categoryId;

                    _classifiedRepository.Add(model);
                    _classifiedRepository.Assignlocations(model.Id, locationId);
                    if (AttributName != null) _securityService.AssignAttributes(model.Id, AttributName);
                    var value = string.Empty;
                    foreach (var items in attributes)
                    {
                        value = formCollection[items.Attr_Name];
                        if (!string.IsNullOrEmpty(value))
                        {
                            var Attr = new ClassifiedAttribute()
                                           {
                                               Attr_Id = items.Id,
                                               ClassifiedId = model.Id,
                                               Value = value
                                           };
                            _clasifiedAttributeRepository.Add(Attr);
                        }

                    }

                    return RedirectToAction("List");

                }
            }

            ModelState.AddModelError("", "Please select a category.");
            ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.DisplayOrder), "Id", "Name");
           ViewBag.UserId = new SelectList(_securityService.GetUsers().Where(x => x.IsActive), "Id", "UserName");
            return View(model);



        }

        public ActionResult Edit(int id)
        {

            var currentclassified = _classifiedRepository.GetById(id);
            ViewBag.Attributes = _classifiedRepository.AttributeValues();

            if (currentclassified == null)
                return RedirectToAction("List");

            var data = _classifiedAdCategoryRepository.GetById(currentclassified.CategoryId);

            ViewBag.AttributeList =
                _categoryAttributeRepository.GetMany(
                    x =>
                    x.CategoryId == data.Id || x.CategoryId == data.ParentCategoryId).ToList();

            ViewBag.Classified_Attr_Textvalue =
                _clasifiedAttributeRepository.GetMany(x => x.ClassifiedId == currentclassified.Id).ToList();

            var currentllocation = currentclassified.Locations.FirstOrDefault();


            if (currentllocation != null)
            {
                ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.DisplayOrder), "Id", "Name", currentllocation.CountryId);
                var currency = _currencyRepository.GetById(x => x.CountryId == currentllocation.CountryId);
                if(currency!=null)
                {
                    ViewBag.CurCode = currency.ISO_Code;
                }
            }

            return View(currentclassified);
        }

        public ActionResult GetAttributeValueList(string categoryId)
        {
            var id = int.Parse(categoryId);
            var data = _classifiedAdCategoryRepository.GetById(x => x.Id == id);

            var Classified_Attr_Textvalue = _clasifiedAttributeRepository.GetMany(x => x.ClassifiedId == id).ToList();
            var list = _categoryAttributeRepository.GetMany(x => x.CategoryId == data.Id || x.CategoryId == data.ParentCategoryId).ToList();

            var att_list = list.Select(i => new ClassifiedCategoryAttribute
          {
              Id = i.Id,
              Attr_Name = i.Attr_Name,
              Attr_Label = i.Attr_Label,
              AttributeControlTypeId = i.AttributeControlTypeId,
              AttributeValues = i.AttributeValues.Select(x => new AttributeValue
              {
                  Id = x.Id,
                  Value = x.Value
              }).ToList()


          });
            return Json(new { AttributeList = att_list }, JsonRequestBehavior.AllowGet);
        }



        //
        // POST: /Admin/Classified/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ClassifiedAd model, List<int> CategoryParent, List<int> locationParent, List<int> AttributName, FormCollection formCollection)
        {

            var attributes = new List<ClassifiedCategoryAttribute>();
            foreach (var i in CategoryParent)
            {

                var data1 = _categoryAttributeRepository.GetMany(
                    x => x.CategoryId == i || x.CategoryId == i).ToList();
                attributes = attributes.Union(data1).ToList();
            }
            var locationId = 0;
            var categoryId = Convert.ToInt32(CategoryParent.LastOrDefault(x => x != 0));
            if (locationParent != null)
            {
                locationId = Convert.ToInt32(locationParent.LastOrDefault(x => x != 0));
            }

            if (categoryId != 0 && locationId != 0)
            {

                if (ModelState.IsValid)
                {
                    model.SubmitDate = DateTime.UtcNow;
                    model.UpdatedOnUtc = DateTime.UtcNow;
                    model.CategoryId = categoryId;
                    _classifiedRepository.Update(model);

                    _securityService.Assignlocations(model.Id, locationId);
                    if (AttributName == null)
                        AttributName = new List<int>();
                    _securityService.AssignAttributes(model.Id, AttributName);

                    var value = string.Empty;
                    _clasifiedAttributeRepository.Delete(x => x.ClassifiedId == model.Id);
                    foreach (var items in attributes)
                    {
                        value = formCollection[items.Attr_Name];
                        if (!string.IsNullOrEmpty(value))
                        {
                            var Attr = new ClassifiedAttribute()
                                           {
                                               Attr_Id = items.Id,
                                               ClassifiedId = model.Id,
                                               Value = value
                                           };
                            _clasifiedAttributeRepository.Add(Attr);
                        }

                    }


                    return RedirectToAction("List");


                }
            }
            ModelState.AddModelError("", "Please select a category.");
            var currentclassified = _classifiedRepository.GetById(model.Id);
            var currentllocation = currentclassified.Locations.FirstOrDefault();
            ViewBag.Country = new SelectList(_countryRepository.GetAll().OrderBy(x => x.DisplayOrder), "Id", "Name", currentllocation.CountryId);
            return View(model);
        }






        public ActionResult Delete(int id)
        {
            var data = _classifiedRepository.GetById(id);
            if (data != null)
                _classifiedRepository.Delete(data);
            return RedirectToAction("List");
        }
        //public PartialViewResult CategoryList(int? page)
        //{
        //    var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
        //    var categories = GetAllServiceCategoriesWithBreadCrumb().ToPagedList(currentPageIndex, 10);

        //    //return PartialView(categories);
        //    //var data = _classifiedAdCategoryRepository.GetAll().OrderBy(x => x.Id);
        //    //return PartialView("_PartialClassifiedCategoryList", data);
        //}

        public List<SelectListItem> GetCategories(int selectedId)
        {
            var categories = _classifiedAdCategoryRepository.GetMany(x => x.IsActive && x.Deleted == false && x.ParentCategoryId == 0 ).ToList();

            categories.Insert(0, new ClassifiedCategory { Name = "[All]", Id = 0 });
            var selectList = new List<SelectListItem>();
            foreach (var c in categories)
                selectList.Add(new SelectListItem()
                {
                    Value = c.Id.ToString(),
                    Text = c.GetClassifiedCategoryBreadCrumb(_classifiedAdCategoryRepository),
                    Selected = c.Id == selectedId
                });
            return selectList;

            //var selectList = new SelectList(categories, "Id", "Name", selectedId);
            // return new JsonResult { Data = selectList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public ActionResult Categories(int selectId, int? page)
        {

            ViewBag.CategoryList = GetCategories(selectId);
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            GetAllServiceCategoriesWithBreadCrumb(selectId);

            var data1 = categories.OrderBy(x => x.Name).ToPagedList(currentPageIndex, 10);
            return View(data1);

        }

        public ActionResult AttributeList(int id, string seName)
        {
            var data = _categoryAttributeRepository.GetMany(x => x.CategoryId == id);
            ViewBag.CategoryName = _classifiedAdCategoryRepository.GetById(id).Name;
            return View("AttributeListByCategory", data);
        }
        public ActionResult CreateCategory()
        {

            var model = new ClassifiedCategory();
            ViewBag.ParentCategoryId = GetAllCategories(0);
            if (Request.IsAjaxRequest())
            {
                return PartialView(model);
            }
            return View(model);
        }

        public ActionResult EditCategory(int id)
        {
            var categories = new List<SelectListItem>();
            var data = _classifiedAdCategoryRepository.GetById(id);
            if (Request.IsAjaxRequest())
            {
                categories = GetAllCategories(data.ParentCategoryId);
                //if (data.SubParentCategoryId != 0)
                //{
                //    categories = GetAllCategories(data.SubParentCategoryId);
                //}
                //if (data.ParentCategoryId != 0)
                //{
                //    categories = GetAllCategories(data.ParentCategoryId);
                //}

                ViewBag.ParentCategoryId = categories;
                return PartialView(data);
            }
            return View(data);
        }

        [HttpPost]
        public ActionResult EditCategory(ClassifiedCategory model)
        {
            if (ModelState.IsValid)
            {

                var currentdata = _classifiedAdCategoryRepository.GetById(model.Id);
                currentdata.ParentCategoryId = model.ParentCategoryId;
               
                currentdata.Name = model.Name;
                currentdata.IsPriceShown = model.IsPriceShown;
                currentdata.IsActive = model.IsActive;
                currentdata.Description = model.Description;
                currentdata.ParentCategoryId = model.ParentCategoryId;
                _classifiedAdCategoryRepository.Update(currentdata);
                return RedirectToAction("Categories", new { selectId = model.ParentCategoryId });

            }
            ViewBag.ParentCategoryId = GetAllCategories(model.ParentCategoryId);
            this.Response.StatusCode = 400;
            return PartialView(model);
        }

        public ActionResult DeleteCategory(int id)
        {
            var data = _classifiedAdCategoryRepository.GetById(id);
            if (data != null)
                _classifiedAdCategoryRepository.Delete(data);
            return RedirectToAction("Categories", new { selectId = 0 });

        }

        [HttpPost]
        public ActionResult CreateCategory(ClassifiedCategory model)
        {

            if (ModelState.IsValid)
            {

                model.CreatedOnUtc = DateTime.Now;
                model.DisplayOrder = 0;
                model.ShowOnHomePage = false;

                _classifiedAdCategoryRepository.Add(model);
                return RedirectToAction("Categories", new { selectId = model.ParentCategoryId });


            }


            this.Response.StatusCode = 400;
            return PartialView(model);

        }
        public List<SelectListItem> GetAllCategories(int selectedId)
        {
            var categories = _classifiedAdCategoryRepository.GetMany(x => x.IsActive && x.Deleted == false).ToList();

            categories.Insert(0, new ClassifiedCategory { Name = "[None]", Id = 0 });
            var selectList = new List<SelectListItem>();
            foreach (var c in categories)
                selectList.Add(new SelectListItem()
                {
                    Value = c.Id.ToString(),
                    Text = c.Name, //c.GetClassifiedCategoryBreadCrumb(_classifiedAdCategoryRepository),
                    Selected = c.Id == selectedId
                });
            return selectList;

            //var selectList = new SelectList(categories, "Id", "Name", selectedId);
            // return new JsonResult { Data = selectList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        public List<ClassifiedCategory> categories = new List<ClassifiedCategory>();
        public List<ClassifiedCategory> data = new List<ClassifiedCategory>();
        public void GetAllServiceCategoriesWithBreadCrumb(int id)
        {
            // var data = new List<ClassifiedCategory>();
            if (id == 0)
            {
                data = _classifiedAdCategoryRepository.GetAll().ToList();
            }
            else
            {
                data = data.Union(_classifiedAdCategoryRepository.GetMany(x => x.Id == id)).ToList();
                var parent = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == id).ToList();
                data = data.Union(parent).ToList();
                foreach (var classifiedCategory in parent)
                {
                    GetAllServiceCategoriesWithBreadCrumb(classifiedCategory.Id);
                    // data = data.Union(p).ToList();
                }
            }

            categories = data.Select(item => new ClassifiedCategory
              {
                  Id = item.Id,
                  Name = item.GetClassifiedCategoryBreadCrumbMore(_classifiedAdCategoryRepository),
                  IsActive = item.IsActive,
                  Description = item.Description,
                  ClassifiedCategoryAttributes = item.ClassifiedCategoryAttributes

              }).ToList();

        }
        [HttpPost]
        public ActionResult LoadLocationByCountry(string id)
        {
            if (id == "")
            {
                id = "0";
            }
            var countryId = Convert.ToInt32(id);
            var currency_ISO = "";
            var currency = _currencyRepository.GetById(x => x.CountryId == countryId);
            var locationparent = _locationRepository.GetMany(x => x.CountryId == countryId && x.ParentId == 0).ToList();
            var data = locationparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });
            if(currency !=null)
            {
                currency_ISO = currency.ISO_Code;
            }
            return Json(new{locationlist=data,ISO=currency_ISO}, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult LoadCategoryChild(string id)
        {
            var categoryId = Convert.ToInt32(id);
            var categoryparent = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == categoryId).ToList();
            var data = categoryparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });
            return Json(new { list = data, guid = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult LoadLocationByLocationId(string id)
        {

            var parentId = Convert.ToInt32(id);
            var locationparent = _locationRepository.GetMany(x => x.ParentId == parentId).ToList();
            var data = locationparent.Select(i => new ClassifiedCategory());
            if (parentId == 0)
            {
                locationparent = new List<Location>();
            }

            data = locationparent.Select(i => new ClassifiedCategory
            {
                Id = i.Id,
                Name = i.Name
            });

            return Json(new { list = data, guid = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult locationHierarchy(string parentId, string id)
        {

            var locationparentId = Convert.ToInt32(parentId);
            var categoryparent = _locationRepository.GetMany(x => x.ParentId == locationparentId).ToList();
            var data = new SelectList(categoryparent, "Id", "Name", id);
            var location = _locationRepository.GetById(x => x.Id == locationparentId);
            var data1 = new Location();
            var guid = Guid.NewGuid();
            if (location != null)
            {
                data1 = new Location
                {
                    ParentId = location.ParentId,
                    Id = location.Id,

                };


            }
            else
            {
                data1 = null;
            }

            return Json(new { selctlist = data, locationparent = data1, Guid = guid }, JsonRequestBehavior.AllowGet);
        }

      
        [HttpPost]
        public ActionResult GetPriceShown(string id)
        {
            var categoryId = Convert.ToInt32(id);
            var data = _classifiedAdCategoryRepository.GetById(x => x.Id == categoryId).IsPriceShown;
            return Json(data, JsonRequestBehavior.AllowGet);
        }
       
        [HttpPost]
        public ActionResult LoadArrtributes(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return null;
            }
            var categoryId = Convert.ToInt32(id);
            var list =
                _categoryAttributeRepository.Filter(x => x.CategoryId == categoryId).ToList();
            var data = list.Select(i => new ClassifiedCategoryAttribute
            {
                Id = i.Id,
                Attr_Name = i.Attr_Name,
                Attr_Label = i.Attr_Label,
                AttributeControlTypeId = i.AttributeControlTypeId,
                AttributeValues = i.AttributeValues.Select(x => new AttributeValue
                {
                    Id = x.Id,
                    Value = x.Value
                }).ToList()


            });
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public PartialViewResult ClassifiedAdsPictures(int id)
        {
            var data = _classifiedPictureRepositories.GetMany(x => x.ClassifiedId == id && x.Deleted == false).OrderByDescending(x => x.Id).ToList();
            return PartialView(data);
        }
        public ActionResult DeleteClassifiedPicture(int id, int classifiedId)
        {

            var classified = _classifiedRepository.GetById(classifiedId);

            var picture = _classifiedPictureRepositories.GetById(id);
            if (picture.ClassifiedId == classified.Id)
            {
                _classifiedPictureRepositories.Delete(picture);

                var fullName = Server.MapPath("~/Content/classified/") + Path.GetFileName(picture.ImageGuid);
                if (System.IO.File.Exists(fullName))
                {
                    try
                    {
                        System.IO.File.Delete(fullName);
                    }
                    catch (Exception)
                    {
                        //Need to add log in admin reporting
                        throw;
                    }

                }

            }

            return RedirectToAction("Edit", new { id = classifiedId });
        }


        [HttpPost]
        public ActionResult UploadImages(int id, IEnumerable<HttpPostedFileBase> attachments)
        {
            var imgGuid = string.Empty;
            var fileName = string.Empty;

            foreach (var file in attachments)
            {
                var fileext = Path.GetExtension(file.FileName);
                if (fileext != ".jpg" && fileext != ".png" && fileext != ".jpeg") continue;
                var coverfilename = Guid.NewGuid() + Path.GetExtension(file.FileName);
                var path = Server.MapPath("~/Content/classified/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var finalpath = Path.Combine(path, coverfilename);
                file.SaveAs(finalpath);
                imgGuid = coverfilename;
                fileName = file.FileName;
                var picture = new ClassifiedPicture()
                {
                    Deleted = false,
                    UploadedOnUtc = DateTime.UtcNow,
                    ClassifiedId = id,
                    ImageName = fileName,
                    ImageGuid = imgGuid

                };
                _classifiedPictureRepositories.Add(picture);

            }
            var res = Json(new { guid = imgGuid, filename = fileName });

            return res;

        }

        [HttpPost]
        public ActionResult Remove(string[] fileNames)
        {
            //   var user = _authenticationService.GetAuthenticatedUser();

            foreach (var fileName in fileNames)
            {

                var fullName = Server.MapPath("~/Content/classified/") + Path.GetFileName(fileName);
                var images = _classifiedPictureRepositories.GetMany(x => x.ImageGuid == fileName).FirstOrDefault();
                if (images != null)
                    _classifiedPictureRepositories.Delete(images);
                if (System.IO.File.Exists(fullName))
                {
                    try
                    {
                        System.IO.File.Delete(fullName);
                    }
                    catch (Exception)
                    {
                        //Need to add log in admin reporting
                        throw;
                    }

                }

            }

            var res = Json(new { success = "success" });
            return res;
        }

        [HttpGet]
        public JsonResult GetClassifiedAdsLocations(int Id, int parentId)
        {
            var data = _locationRepository.GetAll().Where(x => x.ParentId == parentId && x.IsActive).ToList();
            if (Id == null || Id == 0)
                return Json(data, JsonRequestBehavior.AllowGet);
            var currentdata = _classifiedRepository.GetById(Id);
            foreach (var item in currentdata.Locations)
            {
                data.RemoveAt(data.FindIndex(x => x.Id == item.Id));
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Attributes(int? page)
        {
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var data = _categoryAttributeRepository.GetAll().ToPagedList(currentPageIndex, 10);
            return View(data);
        }
        public ActionResult CreateAttributes()
        {

            ViewBag.CategoryId = GetAllCategories(0);
            return PartialView();
        }
        [HttpPost]
        public ActionResult CreateAttributes(ClassifiedCategoryAttribute model)
        {
            if (ModelState.IsValid)
            {
                if (_categoryAttributeRepository.IsAttrNameAvailabel(model.Attr_Name))
                {
                    _categoryAttributeRepository.Add(model);
                    int? page = 1;
                    var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
                    var data = _categoryAttributeRepository.GetAll().ToPagedList(currentPageIndex, 10);
                    return View("Attributes", data);
                }
                else
                {
                    ModelState.AddModelError("AttributesName", ErrorCodeToString(MembershipCreateStatus.DuplicateUserName));
                    return PartialView(model);
                }


            }
            this.Response.StatusCode = 400;
            return PartialView(model);
        }
        public ActionResult EditAttributes(int id)
        {
            var data = _categoryAttributeRepository.GetById(id);
            ViewBag.CategoryId = GetAllCategories(data.CategoryId);
            return PartialView(data);
        }
        [HttpPost]
        public ActionResult EditAttributes(ClassifiedCategoryAttribute model)
        {
            if (ModelState.IsValid)
            {
                if (_categoryAttributeRepository.IsAttrNameAvailabel(model.Attr_Name))
                {
                    _categoryAttributeRepository.Update(model);
                    int? page = 1;
                    var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
                    var data = _categoryAttributeRepository.GetAll().ToPagedList(currentPageIndex, 10);
                    return View("Attributes", data);
                }
                else
                {
                    ModelState.AddModelError("AttributesName", ErrorCodeToString(MembershipCreateStatus.DuplicateUserName));
                    return PartialView(model);
                }
                //return RedirectToAction("Attributes");
            }
            this.Response.StatusCode = 400;
            return PartialView(model);
        }
        public ActionResult DeleteAttributes(int id)
        {
            _categoryAttributeRepository.Delete(x => x.Id == id);
            return RedirectToAction("Attributes");
        }

        public ActionResult AttributesVaulues(int id)
        {
            var categoryatrr = _categoryAttributeRepository.GetById(id);
            var data = _attributeValueRepository.GetMany(x => x.Attr_Id == id);
            ViewBag.CategoryName = categoryatrr.ClassifiedCategories.Name;
            ViewBag.AttributesID = id;
            ViewBag.AttributesName = categoryatrr.Attr_Name;
            return View(data);
        }
        public ActionResult CreateAttributesVaulues(int id)
        {
            var model = new AttributeValue();
            model.Attr_Id = id;
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult CreateAttributesVaulues(AttributeValue model)
        {
            if (ModelState.IsValid)
            {
                _attributeValueRepository.Add(model);
                //var data = _attributeValueRepository.GetMany(x => x.Attr_Id == model.Attr_Id);
                //return View("AttributesVaulues",data);
                return RedirectToAction("AttributesVaulues", new { id = model.Attr_Id });
            }
            this.Response.StatusCode = 400;
            return PartialView(model);
        }
        public ActionResult EditAttributesVaulues(int id)
        {
            var data = _attributeValueRepository.GetById(id);
            return PartialView(data);
        }
        [HttpPost]
        public ActionResult EditAttributesVaulues(AttributeValue model)
        {
            if (ModelState.IsValid)
            {
                _attributeValueRepository.Update(model);
                var data = _attributeValueRepository.GetMany(x => x.Attr_Id == model.Id);
                return View("AttributesVaulues", data);
            }
            this.Response.StatusCode = 400;
            return PartialView(model);
        }
        public ActionResult DeleteAttributesVaulues(int id)
        {
            var data = _attributeValueRepository.GetById(id);
            _attributeValueRepository.Delete(x => x.Id == id);
            return RedirectToAction("AttributesVaulues", new { id = data.Attr_Id });

        }

        //public void adcategoriesHierarchy(int categoryParentId)
        //{
        //    var mylist = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == categoryParentId);
        //    //  draw this list in combo
        //    //  we will switch back to this parent for generatin next combo
        //    var category = _classifiedAdCategoryRepository.GetById(categoryParentId);
        //    if (category != null) adcategoriesHierarchy(category.ParentCategoryId);
        //}
        [HttpPost]
        public ActionResult AdcategoriesHierarchy(string parentId, string id)
        {

            var categoryId = Convert.ToInt32(parentId);
            var categoryparent = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == categoryId).ToList();
            var data = new SelectList(categoryparent, "Id", "Name", id);
            var category = _classifiedAdCategoryRepository.GetById(x => x.Id == categoryId);
            var data1 = new ClassifiedCategory();
            var guid = Guid.NewGuid();
            if (category != null)
            {
                data1 = new ClassifiedCategory
                               {
                                   ParentCategoryId = category.ParentCategoryId,
                                   Id = category.Id,

                               };


            }
            else
            {
                data1 = null;
            }

            return Json(new { selctlist = data, categoryparent = data1, Guid = guid }, JsonRequestBehavior.AllowGet);
        }


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }

}
